import { login } from '@/api/user'
import router from '@/router'
import { getToken, setToken, removeToken } from '@/utils/auth'


export const state = {
  token: getToken(),
  userInfo: {}
}


export const getters = {


}


export const mutations = {
  // 存token
  saveToken(state, token) {
    state.token = token
  },
  // 存用户信息
  saveUserInfo(state, userInfo) {
    state.userInfo = userInfo
  },
  removeToken() {
    removeToken()
  }
}


export const actions = {
  async login(context, payload) {
    const res = await login(payload)
    console.log(res.data.user)
    setToken(res.data.token.token) // 存一份token在cookie
    context.commit('saveToken', res.data.token.token)
    context.commit('saveUserInfo', res.data.user)
  },
  logout(context) {
    removeToken()
    context.commit('saveToken', '')
    context.commit('saveUserInfo', {})
    router.push('/login')
  }


}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}


